import Vue from 'vue'
import axios from 'axios'
import router from '@/router'
import { Message } from "element-ui";

//接口
axios.defaults.baseURL = 'http://127.0.0.1:90';  // 测试环境

//超时时间
axios.defaults.timeout = 20000

//请求前
axios.interceptors.request.use(config => {
	//统一在http请求的header都加上token
	if (localStorage.getItem('token')) {
		config.headers.token = localStorage.getItem('token');
	}
	return config;
},error=>{
	return Promise.reject(err);
})

//请求后
axios.interceptors.response.use(
    response => {
		//token过期处理
		if(response.data.code == 1901){
			Message({
				message: '身份已过期,请重新登录!',
				type: 'error'
			});
			router.push('/login');
			localStorage.clear();
		}
        return response.data;
    },
    error => {
		Message({
			message: '服务器响应失败',
			type: 'warning'
		});
		return Promise.reject(error.response.data)
	}
);

//每进入一个页面，token不存在则跳到登录
router.beforeEach((to, from, next) => {
	let token = localStorage.getItem('token');
    if (!token && to.path != '/login'){
		next({
			path:'/login'
		})
	}
	else{
		next();
	}
});
